import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author wangj881
 * @date 2024-11-22 10:21
 */
public class L349_2 {

    public static void main(String[] args) {
        int[] nums1 = {4, 9, 5};
        int[] nums2 = {9, 4, 9, 8, 4};

        int[] intersection = new Solution().intersection(nums1, nums2);
        System.out.println(Arrays.toString(intersection));

    }

    static class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            Set<Integer> set = new HashSet<>(nums1.length);
            int[] tmp = new int[nums1.length];
            int index = 0;
            for (int i : nums1) {
                set.add(i);
            }
            for (int i : nums2) {
                if (set.contains(i)) {
                    tmp[index] = i;
                    index++;
                    set.remove(i);
                }
            }
            int[] res = new int[index];
            if (index >= 0) System.arraycopy(tmp, 0, res, 0, index);
            return res;
        }
    }

}
